package com.yc.qunxing.web;

import com.yc.qunxing.utils.CreateVerificationCodeImageUtil;
import com.yc.qunxing.utils.CreateVerificationCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/image")
@Slf4j
public class ImageCodeController {

    @Autowired
    private RedisTemplate redisTemplate;


    @RequestMapping
    public void getImageCode(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String vericode = CreateVerificationCodeUtil.getSecurityCode();
        HttpSession session = req.getSession();
        String sessionId = session.getId();
        System.out.println("sessionId = " + sessionId);
        System.out.println("vericode = " + vericode);
        redisTemplate.opsForValue().set(sessionId, vericode, 5, TimeUnit.MINUTES); // 设置验证码过期时间为5分钟
/*        session.setAttribute("verityCode", vericode);*/
        log.info("Generated verification code: {}", vericode);

        resp.setContentType("image/jpeg");
        //浏览器不缓存响应内容--验证码图片，点一次就要刷新一次，所以不能有缓存出现
        resp.setHeader("Pragma", "No-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);

        ImageIO.write(new CreateVerificationCodeImageUtil(vericode).createImage(), "JPEG", resp.getOutputStream());
    }
}